/**
 * 公司（添加|修改）companyOption.js
 * 版本号： v1.0.0
 */
$(function(){
    //限制字段输入长度
    limitFieldLength();
    //所属公司下拉树
    $.ajax({
        url: CONTEXT_PATH + "/company/getTreeCompany.do",
        type: "get",
        success: function (data) {
            $("#parentIdTree").combotree("loadData",JSON.parse(data));
            $("#parentIdTree").combotree({
                onSelect:function(node){
                    var companyId =  $('#companyId_').val();
                    if(null != companyId && companyId != ""){
                        var parentId = $('#parentId').val();
                        // 根节点parentId为"0"情况下，不能修改
                        if(parentId == 0){
                            $.messager.show({ title:"系统提示", msg: "根节点不能选择父节点！", timeout:3000, showType:"slide" });
                            $('#parentIdTree').combotree('setValue', "");
                            return;
                        }
                        if(companyId == node.id || companyId < node.id ){
                            // 修改父节点不能与当前节点相同或比当前节点大
                            $('#parentIdTree').combotree('setValue', parentId);
                            $.messager.show({ title:"系统提示", msg: "子公司与所属公司不能相同,且不能选择则公司为所属公司！", timeout:3000, showType:"slide" });
                            return;
                        }
                    }
                    $('#parentId').val(node.id);
                }
            });
            //新增时自动绑定所属公司
            var companyId = $('#companyId_').val();
            if(companyId == null || companyId == ""){
                var defaultCompanyId = $('#defaultCompanyId').val();
                if(defaultCompanyId != null && defaultCompanyId != "" && defaultCompanyId != "0"){
                    $('#parentIdTree').combotree('setValue', defaultCompanyId);
                    $('#parentId').val(defaultCompanyId);
                }
            }
            //修改操作时，数据加载完成后给父级公司赋值
            var parentId =$('#parentId').val();
            if(parentId != null && parentId != 0 && parentId != ""){
                var array = JSON.parse(data);
                var existFlag = true;
                array.forEach(function(val,index){
                    if(parentId == val.id){
                        existFlag = false;
                    }
                });
                //子账号进行修改根节点时，获取所属公司
                if(existFlag){
                    $.ajax({
                        url: CONTEXT_PATH + "/company/getParentComp.do?parentId="+parentId,
                        type: "get",
                        success: function (data1) {
                           var parentComp =  JSON.parse(data1);
                           var parentName = parentComp.name;
                           if(parentName != "" && parentName != null){
                               var themecombo = "[{\"text\": \""+parentName+"\", \"id\": \""+parentId+"\"}]";
                               $("#parentIdTree").combotree("loadData",JSON.parse(themecombo));
                           }
                        }
                    })
                }
                $('#parentIdTree').combotree('setValue', parentId);
            }
        }
    });

    //操作按钮点击
    $('#optionCompany').bind('click', function(){
        var params = $("#operate_form").serialize();
        $("#operate_form").form("submit",{
            cache:false,
            data: params,
            url: CONTEXT_PATH + "/company/companySave.do",
            onSubmit:function() {
                preventSubmit('operate_form','optionCompany');
                return $(this).form("validate");
            },
            success:function(data) {
                var obj = JSON.parse(data);
                var url = CONTEXT_PATH + "/company/index.do";
                saveJump(obj,url);
            }
        });
    });

    //上传操作
    $('#uploadBtn').bind('click', function(){
        var companyIdInit = $('#companyIdInit_').val();
        var companyId = $('#companyId_').val();
        if(companyId && companyId == companyIdInit){
            uploadFileAndUpdateLogo('uploadBtn', 'uploadfile', 'fileName', 'fileId', 'url', 'size', 'fix', 'md5');
        }else{
            uploadFile('uploadBtn', 'uploadfile', 'fileName', 'fileId', 'url', 'size', 'fix', 'md5', '');
        }
    });

    //图片浏览
    $('#browseBtn').bind('click', function(){
        var fileId = $('#fileId').val();
        if(fileId != null && fileId != ""){
            $.ajax({
                url: CONTEXT_PATH + "/commonFile/getFileUrlById.do?id=" + fileId,
                type: "get",
                success: function (data) {
                    var url = data.message;
                    var imgDiv = $('#browseBtn');
                    if(url != "" && url != null){
                        imgDiv.attr('src',url);
                    }else{
                        imgDiv.attr('src',"");
                        $.messager.show({ title:'提示', msg: '服务器端图片已不存在!', timeout:3000, showType:"slide" });
                        return;
                    }
                    imgDiv.trigger("custom");
                }
            });
        }else{
            $.messager.show({ title:'提示', msg: '请上传图片后再浏览!', timeout:3000, showType:"slide" });
            return;
        }
    });

    //文件选择改变后调整
    $('#uploadfile').filebox({
        onChange:function(n,o){
            $('#uploadBtn').linkbutton('enable');
        }
    });
    //修改时填入文件名称
    var compLogoName = $('#fileName').val();
    if(compLogoName != null && compLogoName != ""){
        $('#uploadfile').filebox({prompt:compLogoName});
    }

    //选择不同证件类型，进行校验
    $('#masterCertType_').combobox({
        onChange: function (newValue, oldValue) {
            $('#masterCertTypeHd').val(newValue);
            var certType = $('#masterCertType_').combobox('getText');
            if(null != certType && certType != ""){
                switch (certType) {
                    case "居民身份证":
                        $('#masterCertNum_').textbox('textbox').validatebox('options').validType=['idcard','length[1,18]'];
                        break;
                    case "士官证":
                        $('#masterCertNum_').textbox('textbox').validatebox('options').validType=['checkOfficers','length[1,11]'];
                        break;
                    case "学生证":
                        $('#masterCertNum_').textbox('textbox').validatebox('options').validType='length[1,15]';
                        break;
                    case "驾驶证":
                        $('#masterCertNum_').textbox('textbox').validatebox('options').validType=['isDriverLicense','length[1,12]'];
                        break;
                    case "护照":
                        $('#masterCertNum_').textbox('textbox').validatebox('options').validType=['ispassport','length[1,9]'];
                        break;
                    case "港澳通行证":
                        $('#masterCertNum_').textbox('textbox').validatebox('options').validType=['hkAndMaPass','length[1,9]'];
                        break;
                    default:
                        $('#masterCertNum_').textbox('textbox').validatebox('options').validType='length[1,11]';
                }
            }
        }
    });

    //加载法人证件类型
    $.ajax({
        url: CONTEXT_PATH + '/commonDict/getCommonDictOptions.do?modelCode=US&funCode=masterCertType',
        type: "get",
        success: function (data) {
            var themecombo = [{'text': '--请选择--', 'value': ''}];
            for (var i = 0; i < data.length; i++) {
                themecombo.push({"text": data[i].propertyName, "value": data[i].cdId});
            }
            $("#masterCertType_").combobox("loadData", themecombo);
            var masterCertType = $('#masterCertTypeHd').val();
            if(masterCertType != ""){
                $('#masterCertType_').combobox("setValue",masterCertType);
            }else{
                $("#masterCertType_").combobox("setValue",'');
            }
        }
    })
});

/**
 * 上传公司logo成功后，修改页面头部logo
 * @param uploadBtn
 * @param uploadfile
 * @param fileName
 * @param fileId
 * @param url
 * @param size
 * @param fix
 * @param md5
 * @returns {boolean}
 */
function uploadFileAndUpdateLogo(uploadBtn, uploadfile, fileName, fileId, url, size, fix, md5){
    if($("#" + uploadBtn).linkbutton('options').disabled == false){
        var file = $("#" + uploadfile).filebox('getValue');
        if("" == file){
            $.messager.show({ title:'提示', msg: '请选择要上传附件！', timeout:3000, showType:"slide" });
            return false;
        }
        //获取上传文件名称
        var getfileName = file.substring(file.lastIndexOf("\\") + 1);
        //获取文件后缀
        var suffix = getfileName.substring(getfileName.lastIndexOf(".") + 1).toUpperCase();
        if("BMP" != suffix && "JPG" != suffix && "JPEG" != suffix && "PNG" != suffix && "GIF" != suffix){
            $.messager.show({ title:'提示', msg: '上传文件格式有误！', timeout:3000, showType:"slide" });
            return false;
        }
        var dataTypeStr = "json";
        if(isIE()){
            dataTypeStr = "text";
        }else{
            dataTypeStr = "json";
        }
        $('#operate_form').ajaxSubmit({
            url: CONTEXT_PATH + "/upload/uploadFile.do",
            dataType: dataTypeStr,
            type: "post",
            clearForm: false,
            beforeSubmit : function() {
                $.messager.progress({
                    title: '提示',
                    msg: '附件上传中, 请稍候...',
                    text: ''
                });
            },
            complete : function(){
                $.messager.progress('close');
            },
            success : function(data, statusText) {
                //解决IE下载问题
                if(isIE()){
                    data = toJson(data);
                }
                //禁用按钮
                $("#" + uploadBtn).linkbutton({ disabled:true });
                //消息提示
                messager(data);
                //赋值元素
                if("PC_200" == data.code){
                    $("#" + fileId).val(data.result.fileId);
                    $("#" + fileName).val(getfileName);
                    $("#" + url).val(data.result.url);
                    $("#" + size).val(data.result.size);
                    $("#" + fix).val(data.result.fix);
                    $("#" + md5).val(data.result.md5);
                    //回显Logo
                    window.parent.updateLogo(data.result.url);
                }
            },
            error : function(xhr, status, err) {
                $.messager.show({ title:'提示', msg: '附件上传失败！', timeout:3000, showType:"slide" });
            }
        });
        return false;
    }
}




